package com.ihunanren.common.auth;

import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.google.common.base.Throwables;

/**
 * @author kalman03
 */
public class DES {
	
	public final static String DEFAULT_KEY = "ihunanren_tb_12xiaoshi_kalman03";
	
	/**
	 * 加密
	 * @param str 要加密的字符串
	 * @param key 密钥
	 * @return
	 */
	public static String encrypt(String str, String key) {
		try {
			Security.addProvider(new com.sun.crypto.provider.SunJCE());
			//获得密钥
			Key generateKey = getKey(key.getBytes());
			//初始化加密对象		
			Cipher cipher= Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE,generateKey);
			
			return byte2hex(cipher.doFinal(str.getBytes()));
		} catch (Exception e) {
			Throwables.propagate(e);
		}
		return null;
	}

	/**
	 * 解密
	 * @param str 要解密的字符串
	 * @param key 密钥
	 * @return
	 */
	
	public static String decrypt(String str, String key) {
		try {
			Security.addProvider(new com.sun.crypto.provider.SunJCE());
			//获得密钥
			Key generateKey = getKey(key.getBytes());
			//初始化加密对象		
			Cipher cipher= Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE,generateKey);
			return new String(cipher.doFinal(hex2byte(str)));
		} catch (Exception e) {
			Throwables.propagate(e);
		}
		return null;
	}

	/**
	 * 从指定字符串生成密钥,密钥所需的字节数组长度为8位,不足8位时后面补0,超出8位只取前8位
	 * @param array 指定字符串对应的字节数组
	 * @return 生成的密钥
	 */
	private static Key getKey(byte[] array) {
		// 要返回的密钥对象
		Key key = null;
		// 一个默认值为0的8位数组
		byte[] b = new byte[8];
		// 不足8位时后面默认为0,超出8位只取前8位
		for (int i = 0; i < b.length && i < array.length; i++) {
			b[i] = array[i];
		}
		// 生成密钥
		key = new SecretKeySpec(b, "DES");
		return key;
	}
	
	/**
	 * 将字符数组转换为16进制的字符串
	 */
	private static String byte2hex(byte[] data){
		StringBuffer hs = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < data.length; n++) {
            stmp = (java.lang.Integer.toHexString(data[n] & 0XFF));
            if (stmp.length() == 1)
                hs.append("0").append(stmp);
            else
                hs.append(stmp);
        }
        return hs.toString().toUpperCase();
	}
	
	
	/**
	 * 将16进制字符串转换成字节数组
	 * @param str 要转换的16进制字符串
	 * @return 字节数组
	 * @throws Exception
	 */
	private static byte[] hex2byte(String str){
		byte[] arrB = str.getBytes();
		int iLen = arrB.length;
		// 1个byte是2字符，所以字符串的长度是数组长度的两倍
		byte[] arrOut = new byte[iLen / 2];
		for (int i = 0; i < iLen; i = i + 2) {
			String strTmp = new String(arrB, i, 2);
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}
		return arrOut;
	}
//	
//	public static byte[] hex2byte(String str) { // 字符串转二进制
//		str = str.trim();
//		int len = str.length();
//		if (len == 0 || len % 2 == 1)
//			return null;
//		byte[] b = new byte[len / 2];
//		try {
//			for (int i = 0; i < str.length(); i += 2) {
//				b[i / 2] = (byte) Integer.decode("0x" + str.substring(i, i + 2)).intValue();
//			}
//			return b;
//		} catch (Exception e) {
//			Throwables.propagate(e);
//		}
//		return null;
//	}
}
